package com.mgfireworks.mgplatform.mgshop.main;

import cn.hn.java.summer.db.BaseDao;
import cn.hn.java.summer.db.multiple.DataSource1;
import cn.hn.java.summer.exception.BusinessException;
import cn.hn.java.summer.utils.DateUtils;
import cn.hn.java.summer.utils.StringUtils;
import com.mgfireworks.mgplatform.mgshop.comm.CartStatus;
import com.mgfireworks.mgplatform.mgshop.comm.OrderStatus;
import com.mgfireworks.mgplatform.mgshop.db.ProductStock;
import com.mgfireworks.mgplatform.mgshop.db.ShopCart;
import com.mgfireworks.mgplatform.mgshop.db.ShopOrder;
import com.mgfireworks.mgplatform.mgshop.model.*;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by xw2sy on 2017-04-30.
 * 订单管理类
 */
@Service
public class OrderService extends BaseDao<DataSource1> {

    @Autowired
    private AccountService accountService;

    /**
     * 添加产品到购物车
     * @param user 当前用户
     * @param stockId 库存编号
     */
    @Transactional(rollbackFor = Exception.class)
    public void addProductToCart(ShopUserInfoVo user, String stockId) throws BusinessException {
        //1.检查是否设置了收货地址
        user= accountService.getShopUserInfo(user.getUserId());
        if(user==null || user.getReceivingAddress()==null){
            throw new BusinessException("您还未设置收货地址！");
        }
        //2.检查收货地址是否在当前代理商区域内
        // 调用百度地图api取得最终收货地址的位置
        // 再与当前代理商区域范围进行判断
        // TODO: 2017-05-02
        //3.检查是否有足够库存
        StockVo stock=get(StockVo.class, ProductStock.builder().stockId(stockId).build());
        if(stock.getQuantity()<1){
            throw new BusinessException("该产品库存不足！");
        }
        //3.获取原有的购物车清单
        List<ShopCartVo> shopCartVoList;
        shopCartVoList=list(
                ShopCartVo.class,
                ShopCart.builder()
                        .orgId(user.getShopOrgId())
                        .userId(user.getUserId())
                        .status(CartStatus.ENABLE.value())
                .build()
        );
        //找到存在的购物清单项
        ShopCartVo oldCart=shopCartVoList.stream()
                .filter((s)->s.getStockId().equals(stockId))
                .findFirst()
                .orElse(null);
        //更新
        if(oldCart!=null){
            //增加购物车清单项数量，并更新
            oldCart.setAmount(oldCart.getAmount()+1);
            oldCart.setUpdatedTime(DateTime.now().toDate());
            if(update(oldCart)!=1){
                throw  new BusinessException("添加到购物车清单失败！");
            }
            return;
        }
        //新增
        if(insert(
                ShopCart.builder()
                        .orgId(user.getShopOrgId())
                        .userId(user.getUserId())
                        .amount(1)
                        .price(stock.getPrice())
                        .stockId(stockId)
                        .productId(stock.getProductId())
                        .status(CartStatus.ENABLE.value())
                        .createdTime(DateTime.now().toDate())
                        .updatedTime(DateTime.now().toDate())
                .build()
        )!=1){
            throw  new BusinessException("添加到购物车清单失败！");
        }
    }

    /**
     * 取购物车项列表
     * @param user
     * @return
     */
    public List<OrderItemDetail> getCartItems(ShopUserInfoVo user){
        return all("getCartItems",OrderItemDetail.class,user,ce().set("status",CartStatus.ENABLE.value()));
    }

    /**
     * 提交用户购物车订单
     * @param user
     */
    @Transactional(rollbackFor = Exception.class)
    public ShopOrderVo submitOrder(ShopUserInfoVo user) throws BusinessException {
        //1.检查收货地址是否在当前代理商区域内
        //2.取购物车清单
        List<ShopCartVo> shopCartVos=list(ShopCartVo.class,
                ShopCart.builder()
                        .orgId(user.getShopOrgId())
                        .userId(user.getUserId())
                        .status(CartStatus.ENABLE.value())
                .build()
        );
        if(shopCartVos.isEmpty()){
            throw new BusinessException("请先添加产品到购物车再购买！");
        }
        //3.检查是否有足够库存
        //3.1.取库存
        List<CartStockVo> stockVos= all("getCartProductStocks",CartStockVo.class,user);
        //3.2.判断库存等状态、计算总额
        BigDecimal totalAmount=new BigDecimal(0);
        for(CartStockVo s : stockVos){
            if(
                !s.getOnline() || //下架
                s.getOutOfStock() || //缺货
                s.getQuantity()<s.getCartAmount() //库存不足
            ){
                throw new BusinessException("购买的产品已下架或库存不足！");
            }
            //总额
            totalAmount=totalAmount.add(s.getPrice().multiply(new BigDecimal(s.getCartAmount())));
        }
        //4.添加订单
        ShopOrder order= ShopOrder.builder()
                .orderId(
                        //订单号(5位orgId +7位 uid  +2位天  +2位时 +2位分 mm+2位秒 ss)
                        StringUtils.leftPad(user.getShopOrgId().toString(),5,'0')+
                                StringUtils.leftPad(user.getUserId().toString(),7,'0')+
                                DateUtils.now("ddhhmmss")
                ).userId(user.getUserId())
                .itemCount(shopCartVos.size())
                .totalAmount(totalAmount)
                .status(OrderStatus.NO_PAY.value())
                .createdTime(DateTime.now().toDate())
                .updatedTime(DateTime.now().toDate())
                .build();
        //插入数据库
        insert(order);
        //5.将购物车清单状态改为移除状态
        update("updateOrderCartStatus",
            ShopCartVo.builder()
                .orderId(order.getOrderId())
                .orgId(user.getShopOrgId())
                .userId(user.getUserId())
            .build()
        );

        ShopOrderVo orderVo=new ShopOrderVo();
        BeanUtils.copyProperties(order,orderVo);
        return orderVo;
    }

    /**
     * 取订单信息
     * @param user 订单用户
     * @param orderId 订单号
     * @return
     */
    public ShopOrderVo getOrderInfo(ShopUserInfoVo user, String orderId){
        //订单信息
        ShopOrderVo order=
        get(
            ShopOrderVo.class,
            ShopOrder.builder()
                .userId(user.getUserId())
                .orderId(orderId)
            .build()
        );
        //订单项列表
        List<OrderItemDetail> orderItems=
        all(
            "getCartItems",
            OrderItemDetail.class,
            ShopOrder.builder()
                .userId(user.getUserId())
                .orderId(orderId)
                .status(CartStatus.DISABLE.value())
            .build()
        );
        order.setItems(orderItems);
        return order;
    }

    /**
     * 取用户订单列表
     * @param user 用户
     * @return
     */
    public List<ShopOrderVo> getOrders(ShopUserInfoVo user){
        return list("getOrders",ShopOrderVo.class,user);
    }
}
